package com.zbs.framework.dao.rolefunction.repository;

import com.zbs.framework.dao.function.entity.Function;
import com.zbs.framework.dao.permission.entity.Permission;
import com.zbs.framework.dao.rolefunction.entity.RoleFunction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface RoleFunctionRepository extends JpaRepository<RoleFunction, Long>, JpaSpecificationExecutor<RoleFunction> {

    @Query("select distinct p from FunctionPermission fp" +
            " left join Permission p on fp.permissionId = p.id" +
            " inner join RoleFunction rf on fp.functionId = rf.functionId where rf.roleId in :roleIds")
    List<Permission> findPermissions(@Param("roleIds") List<Integer> roleIds);

    @Query("select distinct f from RoleFunction rf" +
            " left join Function f on rf.functionId = f.id" +
            " where rf.roleId in :roleIds")
    List<Function> findFunctions(@Param("roleIds") Integer[] roleIds);


    @Query(value = "SELECT COUNT(*) FROM mnt_role_function rf LEFT JOIN mnt_function f on f.id = rf.function_id WHERE rf.role_id in :roleIds AND f.identifier = :identifier limit 1",nativeQuery = true)
    Integer findFunctions(@Param("roleIds") Integer[] roleIds,String identifier);

    /*@Query("select f from UserFunction rf left join Function f on rf.functionId = f.id where rf.userId = :userId")
    List<Function> findPermissions(@Param("userId") Integer userId);*/

    @Query("select rf.functionId from RoleFunction rf where rf.roleId = :roleId")
    List<Long> findFunctionIds(@Param("roleId") Integer roleId);

    void deleteByRoleIdAndFunctionId(Integer roleId, Long functionId);


    void deleteByRoleId(Integer roleId);
}
